package md.mru.core.repositories;

import md.mru.core.domains.Folder;
import md.mru.core.domains.type.OrderStateType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.EnumSet;
import java.util.List;
import java.util.Set;

/**
 * @author sergiu.marin
 * @since 01.04.2014
 */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public interface FolderRepository extends JpaRepository<Folder, Long> {

    @Query("SELECT f FROM Folder f WHERE f.folderState.id=:folderState")
    public List<Folder> getUnAttachedFolders(@Param(value = "folderState") long folderState);

    @Modifying
    @Query("UPDATE Folder f SET f.folderState.id=:folderStateId WHERE f.id=:folderId")
    public void updateFolderState(@Param(value = "folderStateId") Long folderStateId, @Param(value = "folderId") Long folderId);

    @Deprecated
    @Transactional
    @Modifying
    @Query("UPDATE Folder f SET f.folderState=:generalState, f.folderState=:currentState WHERE f.id=:folderId")
    void save(@Param(value = "folderId") long folderId,
              @Param(value = "generalState") OrderStateType generalState,
              @Param(value = "currentState") OrderStateType currentState);

    @Deprecated
    @Query("SELECT f FROM Folder f WHERE f.folderState IN :orderStates")
    List<Folder> loadFoldersByStates(@Param("orderStates") EnumSet<OrderStateType> orderStates);

    @Query("SELECT f FROM Folder f LEFT JOIN f.user u WHERE u IS NULL")
    List<Folder> loadUnAssociatedFolders();

    @Query("SELECT f FROM Folder f WHERE f.folderState.id IN :folderStateIds")
    List<Folder> loadFoldersByState(@Param(value = "folderStateIds") Set<Long> folderStateIds);

}
